package com.tsinghuabigdata.edu.ddmath.module.login;

import android.content.Context;
import android.os.AsyncTask;

import com.tsinghuabigdata.edu.commons.codec.MD5Utils;
import com.tsinghuabigdata.edu.commons.http.HttpRequestException;
import com.tsinghuabigdata.edu.ddmath.MVPModel.RequestListener;
import com.tsinghuabigdata.edu.ddmath.bean.JoinedClassInfo;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.bean.ResultInfo;
import com.tsinghuabigdata.edu.ddmath.bean.School;
import com.tsinghuabigdata.edu.ddmath.bean.UserDetailinfo;
import com.tsinghuabigdata.edu.ddmath.commons.http.AppAsyncTask;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.module.apkupgrade.UpdateInfo;
import com.tsinghuabigdata.edu.ddmath.requestHandler.LoginReqService;
import com.tsinghuabigdata.edu.ddmath.requestHandler.requestImpl.LoginReqImpl;
import com.tsinghuabigdata.edu.ddmath.util.AsyncTaskCancel;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 28205 on 2016/12/14.
 */
public class LoginModel {
    private LoginReqService loginReqService = new LoginReqImpl();
    private List<AsyncTask> runningTasks = new ArrayList<AsyncTask>();


    /**
     * 登录
     */
    class LoginTask extends BaseLoginTask {
        private RequestListener reqListener;

        public LoginTask(LoginReqService mUserService, Context mContext, RequestListener requestListener) {
            super(mUserService, mContext);
            reqListener = requestListener;
        }

        @Override
        protected void onResult(LoginInfo loginInfo) {
            reqListener.onSuccess(loginInfo);
        }

        @Override
        protected void onFailure(HttpResponse<LoginInfo> response, Exception ex) {
            reqListener.onFail(response, ex);
        }

    }

    /**
     * 退出登录
     */
    class StuLogoutTask extends AppAsyncTask<String, Void, Void> {
        private RequestListener reqListener;

        public StuLogoutTask(RequestListener listener) {
            this.reqListener = listener;
        }

        @Override
        protected Void doExecute(String... params) throws Exception {
            String accessToken = params[0];
            loginReqService.stulogout(accessToken);
            return null;
        }

        @Override
        protected void onResult(Void resultInfo) {
            reqListener.onSuccess(resultInfo);
        }

        @Override
        protected void onFailure(HttpResponse<Void> response, Exception ex) {
            reqListener.onFail(response, ex);
        }
    }

    /**
     * 注册
     */
    class RegisterTask extends AppAsyncTask<String, Void, Void> {
        private RequestListener reqListener;

        public RegisterTask(RequestListener listener) {
            this.reqListener = listener;
        }

        @Override
        protected Void doExecute(String... params) throws Exception {
            String nickName = params[0];
            String cellphone = params[1];
            String passwd = params[2];
            String gender = params[3];
            String verifycode = params[4];
            loginReqService.register(nickName, cellphone, passwd, gender, verifycode);
            return null;
        }

        @Override
        protected void onResult(Void resultInfo) {
            reqListener.onSuccess(resultInfo);
        }

        @Override
        protected void onFailure(HttpResponse<Void> response, Exception ex) {
            reqListener.onFail(response, ex);
        }

    }

    /**
     * 检查APK更新
     */
    class CheckApkupdateTask extends AppAsyncTask<String, Void, UpdateInfo> {
        private RequestListener reqListener;

        public CheckApkupdateTask(RequestListener listener) {
            this.reqListener = listener;
        }

        @Override
        protected UpdateInfo doExecute(String... params) throws Exception {
            return loginReqService.queryApkUpdateinfo();
        }

        @Override
        protected void onResult(UpdateInfo updateInfo) {
            reqListener.onSuccess(updateInfo);
        }

        @Override
        protected void onFailure(HttpResponse<UpdateInfo> response, Exception ex) {
            reqListener.onFail(response, ex);
        }
    }

    /**
     * 个人信息补充
     */
    class UpdateExtraPersoninfoTask extends AppAsyncTask<String, Void, Void> {
        private RequestListener reqListener;

        public UpdateExtraPersoninfoTask(RequestListener listener) {
            this.reqListener = listener;
        }

        @Override
        protected Void doExecute(String... params) throws Exception {
            String accessToken = params[0];
            String accountId = params[1];
            String reallyName = params[2];
//            String schoolId = params[3];
            String enrollmentYear = params[3];
            loginReqService.updateExtraPersoninfo(accessToken, accountId, reallyName, enrollmentYear);
            return null;
        }

        @Override
        protected void onResult(Void resultInfo) {
            reqListener.onSuccess(resultInfo);
        }

        @Override
        protected void onFailure(HttpResponse<Void> response, Exception ex) {
            reqListener.onFail(response, ex);
        }

    }

    /**
     * 学校模糊查询
     */
    public class QueryBlurSchoolTask extends AppAsyncTask<String, Void, List<School>> {
        private RequestListener reqListener;

        public QueryBlurSchoolTask(RequestListener listener) {
            this.reqListener = listener;
        }

        @Override
        protected List<School> doExecute(String... params) throws Exception {
            String schoolName = params[0];
            return loginReqService.queryBlurSchool(schoolName);
        }

        @Override
        protected void onResult(List<School> resultInfo) {
            reqListener.onSuccess(resultInfo);
        }

        @Override
        protected void onFailure(HttpResponse<List<School>> response, Exception ex) {
            reqListener.onFail(response, ex);
        }
    }

    /**
     * 获取验证码
     */
    class GetVerifyCodeTask extends AppAsyncTask<String, Void, Void> {
        private RequestListener reqListener;

        public GetVerifyCodeTask(RequestListener listener) {
            this.reqListener = listener;
        }

        @Override
        protected Void doExecute(String... params) throws Exception {
            String phone = params[0];
            String type = params[1];
            loginReqService.getVeryfyCode(phone, type);
            return null;
        }

        @Override
        protected void onResult(Void verifycode) {
            reqListener.onSuccess(verifycode);
        }

        @Override
        protected void onFailure(HttpResponse<Void> response, Exception ex) {
            reqListener.onFail(response, ex);
        }
    }

    /**
     * 重置密码
     */
    class ResetPassTask extends AppAsyncTask<String, Void, Void> {
        private RequestListener reqListener;

        public ResetPassTask(RequestListener listener) {
            this.reqListener = listener;
        }

        @Override
        protected Void doExecute(String... params) throws Exception {
            String phone = params[0];
            String verifycode = params[1];
            String newPasswd = params[2];
            String confirmPasswd = params[3];
            loginReqService.resetPass(phone, verifycode, newPasswd, confirmPasswd);
            return null;
        }

        @Override
        protected void onResult(Void resultInfo) {
            reqListener.onSuccess(resultInfo);
        }

        @Override
        protected void onFailure(HttpResponse<Void> response, Exception ex) {
            reqListener.onFail(response, ex);
        }

    }

    /**
     * 检查手机是否使用
     */
    class IsPhoneUsedTask extends AppAsyncTask<String, Void, ResultInfo> {
        private RequestListener reqListener;

        public IsPhoneUsedTask(RequestListener listener) {
            this.reqListener = listener;
        }

        @Override
        protected ResultInfo doExecute(String... params) throws Exception {
            String phone = params[0];
            return loginReqService.isPhoneUsed(phone);
        }

        @Override
        protected void onResult(ResultInfo resultInfo) {
            reqListener.onSuccess(resultInfo);
        }

        @Override
        protected void onFailure(HttpResponse<ResultInfo> response, Exception ex) {
            reqListener.onFail(response, ex);
        }
    }

    /**
     * 检查手机是否使用
     */
    class BindMobileTask extends AppAsyncTask<String, Void, Object> {
        private RequestListener reqListener;

        public BindMobileTask(RequestListener listener) {
            this.reqListener = listener;
        }

        @Override
        protected Object doExecute(String... params) throws Exception {
            String accessToken = params[0];
            String loginName = params[1];
            String cellphone = params[2];
            String verifycode = params[3];
            return loginReqService.bindMobile(accessToken, loginName, cellphone, verifycode);
        }

        @Override
        protected void onResult(Object resultInfo) {
            reqListener.onSuccess(resultInfo);
        }

        @Override
        protected void onFailure(HttpResponse<Object> response, Exception ex) {
            reqListener.onFail(response, ex);
        }
    }

    /**
     * 获取班级列表
     */
    class GetJoinedClassTask extends AppAsyncTask<String, Void, List<JoinedClassInfo>> {
        private RequestListener reqListener;

        public GetJoinedClassTask(RequestListener listener) {
            this.reqListener = listener;
        }

        @Override
        protected List<JoinedClassInfo> doExecute(String... params) throws Exception {
            String accessToken = params[0];
            String studentId = params[1];
            return loginReqService.getJoinedClassList(accessToken, studentId);
        }

        @Override
        protected void onResult(List<JoinedClassInfo> resultInfo) {
            reqListener.onSuccess(resultInfo);
        }

        @Override
        protected void onFailure(HttpResponse<List<JoinedClassInfo>> response, Exception ex) {
            reqListener.onFail(response, ex);
        }
    }

    /**
     * 个人基本信息查询
     */
    class QueryUserdetailInfoTask extends AppAsyncTask<String, Void, UserDetailinfo> {
        private RequestListener reqListener;

        public QueryUserdetailInfoTask(RequestListener listener) {
            this.reqListener = listener;
        }

        @Override
        protected UserDetailinfo doExecute(String... params) throws Exception {
            String accessToken = params[0];
            String accountId = params[1];
            return loginReqService.queryUserDetailinfo(accessToken, accountId);
        }

        @Override
        protected void onResult(UserDetailinfo resultInfo) {
            reqListener.onSuccess(resultInfo);
        }

        @Override
        protected void onFailure(HttpResponse<UserDetailinfo> response, Exception ex) {
            reqListener.onFail(response, ex);
        }
    }

    /**
     * 登录调用方法
     *
     * @param userName
     * @param password
     */
    public void login(Context context, String userName, String password, RequestListener requestListener) {
        LoginTask loginTask = new LoginTask(loginReqService, context, requestListener);
        loginTask.execute(userName, MD5Utils.stringToMD5(password));
        runningTasks.add(loginTask);
    }

    /**
     * 检查手机是否使用
     */
    public void isPhoneUsed(String phone, RequestListener requestListener) {
        IsPhoneUsedTask isPhoneUsedTask = new IsPhoneUsedTask(requestListener);
        isPhoneUsedTask.execute(phone);
        runningTasks.add(isPhoneUsedTask);
    }

    /**
     * 退出登录调用方法
     */
    public void logout(String accessToken, RequestListener requestListener) {
        StuLogoutTask stuLogoutTask = new StuLogoutTask(requestListener);
        stuLogoutTask.execute(accessToken);
        runningTasks.add(stuLogoutTask);
    }

    /**
     * 注册
     * register(nickName, cellphone, passwd, gender, verifycode);
     * sex : female 女， male 男
     */
    public void register(String nickName, String cellphone, String password, String gender, String validcode, RequestListener requestListener) {
        RegisterTask registerTask = new RegisterTask(requestListener);
        registerTask.execute(nickName, cellphone, MD5Utils.stringToMD5(password), gender, validcode);
        runningTasks.add(registerTask);
    }

    /**
     * 个人信息补充
     * loginReqService.updateExtraPersoninfo(accessToken, accountId, reallyName, schoolId, sex, enrollmentYear);
     */
    public void updateExtraPersoninfo(String accessToken, String accountId, String reallyName,
                                      String enrollmentYear, RequestListener requestListener) {
        UpdateExtraPersoninfoTask updateExtraPersoninfoTask = new UpdateExtraPersoninfoTask(requestListener);
        updateExtraPersoninfoTask.execute(accessToken, accountId, reallyName, enrollmentYear);
        runningTasks.add(updateExtraPersoninfoTask);
    }

    /**
     * 学校模糊查询
     */
    public void queryBlurSchool(String schoolName, RequestListener requestListener) {
        QueryBlurSchoolTask queryBlurSchoolTask = new QueryBlurSchoolTask(requestListener);
        queryBlurSchoolTask.execute(schoolName);
        runningTasks.add(queryBlurSchoolTask);
    }

    /**
     * 获取验证码
     * type 操作类型(register, passwdRetrieve,binding)
     */
    public void getVerifycode(String phone, String type, RequestListener requestListener) {
        GetVerifyCodeTask getVerifyCodeTask = new GetVerifyCodeTask(requestListener);
        getVerifyCodeTask.execute(phone, type);
        runningTasks.add(getVerifyCodeTask);
    }

    /**
     * 绑定手机
     */
    public void bindMobile(String accessToken, String loginName, String phone, String verifycode, RequestListener requestListener) {
        BindMobileTask bindMobileTask = new BindMobileTask(requestListener);
        bindMobileTask.execute(accessToken, loginName, phone, verifycode);
        runningTasks.add(bindMobileTask);
    }

    /**
     * 检查APK更新
     */
    public void checkApkupdate(RequestListener requestListener) {
        CheckApkupdateTask checkApkupdateTask = new CheckApkupdateTask(requestListener);
        checkApkupdateTask.execute();
        runningTasks.add(checkApkupdateTask);
    }

    /**
     * 获取班级列表
     */
    public void getJoinedClassList(String accessToken, String studentId, RequestListener requestListener) {
        GetJoinedClassTask getJoinedClassTask = new GetJoinedClassTask(requestListener);
        getJoinedClassTask.execute(accessToken, studentId);
        runningTasks.add(getJoinedClassTask);
    }

    /**
     * 重置密码
     * phone = params[0];
     * String verifycode = params[1];
     * String newPasswd = params[2];
     * String confirmPasswd = params[3];
     */
    public void resetPass(String phone, String verifycode, String newpass,
                          String confirmpass, RequestListener requestListener) {
        ResetPassTask resetPassTask = new ResetPassTask(requestListener);
        resetPassTask.execute(phone, verifycode, MD5Utils.stringToMD5(newpass), MD5Utils.stringToMD5(confirmpass));
        runningTasks.add(resetPassTask);
    }

    /**
     * 个人基本信息查询
     */
    public void queryUserdetailInfo(String accessToken, String accountId, RequestListener requestListener) {
        QueryUserdetailInfoTask queryUserdetailInfoTask = new QueryUserdetailInfoTask(requestListener);
        queryUserdetailInfoTask.execute(accessToken, accountId);
        runningTasks.add(queryUserdetailInfoTask);
    }

    /**
     * 个人基本信息查询
     */
    public UserDetailinfo queryUserdetailInfo2(String accessToken, String accountId) throws JSONException, HttpRequestException {
        UserDetailinfo userDetailinfo = loginReqService.queryUserDetailinfo(accessToken, accountId);
        return userDetailinfo;
    }

    public void stopRunningTasks() {
        if (runningTasks.size() > 0) {
            AsyncTaskCancel.cancel(runningTasks);
        }
    }
}
